package cn.yudao.user.service.impl;

import cn.yudao.basic.constant.BaseConstants;
import cn.yudao.basic.dto.RegisterEmailDto;
import cn.yudao.basic.dto.RegisterPhoneDto;
import cn.yudao.basic.exception.BusinessException;
import cn.yudao.basic.utils.MD5Utils;
import cn.yudao.basic.utils.StrUtils;
import cn.yudao.user.domain.Logininfo;
import cn.yudao.user.domain.User;
import cn.yudao.user.mapper.LogininfoMapper;
import cn.yudao.user.mapper.UserMapper;
import cn.yudao.user.service.IUserService;
import cn.yudao.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yudao
 * @since 2022-07-05
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public void registerPhone(RegisterPhoneDto registerPhoneDto) {
        // 非空判断
        if (registerPhoneDto == null){
            throw new BusinessException("参数不能为空，请重新输入！");
        }
        String phone = registerPhoneDto.getPhone(); // 电话
        String password = registerPhoneDto.getPassword(); // 密码
        String charmPassword = registerPhoneDto.getCharmPassword(); // 确认密码
        String registerCode = registerPhoneDto.getRegisterCode(); // 短信验证码
        String imageCode = registerPhoneDto.getImageCode(); // 图片验证码key
        String imageCodeValue = registerPhoneDto.getImageCodeValue(); // 图片验证码内容

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)
        || StringUtils.isEmpty(charmPassword) || StringUtils.isEmpty(registerCode)
                || StringUtils.isEmpty(imageCode) || StringUtils.isEmpty(imageCodeValue)){
            throw new BusinessException("参数不能为空，请重新输入！");
        }
        // 判断短信验证的手机号和注册的手机号是否一致
        String RedisPhoneKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + phone;
        Object redisPhoneValue = redisTemplate.opsForValue().get(RedisPhoneKey);
        if (redisPhoneValue == null){
            throw new BusinessException("请重新输入！");
        }
        // 判断输入的短信验证码是否正确
        String redisPhoneValueRedis = redisPhoneValue.toString().split(":")[1];
        if (!redisPhoneValueRedis.equalsIgnoreCase(registerCode)){
            throw new BusinessException("验证码错误，请重新输入");
        }
        // 判断2次密码是否一致
        if (!password.equals(charmPassword)){
            throw new BusinessException("输入的2次密码不一致，请重新输入");
        }
        // 判断图片验证码是否正确
        Object imageCodeRedisValue = redisTemplate.opsForValue().get(imageCode);
        if (!imageCodeValue.equalsIgnoreCase(imageCodeRedisValue.toString())){
            throw new BusinessException("图片验证码输入错误，请重新输入");
        }
        // 判断用户是否注册过
        User user = userMapper.loadByPhone(phone);
        if (user != null){
            throw new BusinessException("用户已经存在");
        }
        // 将registerPhoneDto对象中的字段值添加给user
         user = RegisterDto2User(registerPhoneDto);
        // 将user添加到数据库
        userMapper.save(user);
        // 将user的数据给logininfo
        Logininfo logininfo = User2Logininfo(user);
        // 添加logininfo到数据库
        logininfoMapper.save(logininfo);
        // 给user设置longininfo_id
        user.setLogininfoId(logininfo.getId());
        // 修改user
        userMapper.upadte(user);
    }

    @Override
    public void registerEmail(RegisterEmailDto registerEmailDto) {
        String email = registerEmailDto.getEmail(); // 邮件
        String password = registerEmailDto.getPassword(); // 密码
        String charmPassword = registerEmailDto.getCharmPassword(); // 确认密码
        String registerCode = registerEmailDto.getRegisterCode(); // 邮件验证码
        String imageCode = registerEmailDto.getImageCode(); // 图片验证码key
        String imageCodeValue = registerEmailDto.getImageCodeValue(); // 图片验证码内容

        // 判断参数是否为空
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(charmPassword) || StringUtils.isEmpty(registerCode)
                || StringUtils.isEmpty(imageCode) || StringUtils.isEmpty(imageCodeValue)){
            throw new BusinessException("参数不能为空，请重新输入！");
        }

        String emailRedisCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + email;
        // 判断2次输入的邮箱是否相同
        Object redisTemValue = redisTemplate.opsForValue().get(emailRedisCodeKey);

        if (redisTemValue == null){
            throw new BusinessException("请重新输入！");
        }
        // 判断2次输入的密码是否相同
        if (!password.equals(charmPassword)){
            throw new BusinessException("密码不一致，请重新输入！");
        }
        // 判断邮件验证码是否输入正确
        String redisValueCode = redisTemValue.toString().split(":")[1];
        if (!registerCode.equalsIgnoreCase(redisValueCode)){
            throw new BusinessException("验证码错误，请重新输入！");
        }
        // 判断用户是否注册
        User user = userMapper.loadByEmail(email);
        if (user != null){
            throw new BusinessException("用户以注册，请直接登录！");
        }
        // 初始化用户
       user =  registerEmailDto2User(registerEmailDto);
        // 将对象添加到user表
        userMapper.save(user);
        // 将user对象的值赋值给logininfo
        Logininfo logininfo = User2Logininfo(user);
        // 将logininfo添加到数据库
        logininfoMapper.save(logininfo);
        // 给user赋值
        user.setLogininfoId(logininfo.getId());
        // 再次修改user
        userMapper.upadte(user);
    }

    @Override
    public User loadByLogininfoId(Long id) {
        User user =  userMapper.loadByLogininfoId(id);
        return user;
    }


    /**
    * @Title: registerEmailDto2User
    * @Description: 邮箱注册对象初始化
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/7 19:00
    * @Parameters:
    * @Return
    */
    private User registerEmailDto2User(RegisterEmailDto registerEmailDto) {
        String email = registerEmailDto.getEmail(); // 邮件
        String password = registerEmailDto.getPassword(); // 密码
        User user = new User();
        user.setEmail(email);
        user.setUsername(email);
        // 获得盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 给密码加密
        String userPassword = MD5Utils.encrypByMd5(salt + password);
        user.setPassword(userPassword);
        // 设置盐值
        user.setSalt(salt);
        return user;
    }

    private User RegisterDto2User(RegisterPhoneDto registerPhoneDto) {
        String phone = registerPhoneDto.getPhone(); // 电话
        String password = registerPhoneDto.getPassword(); // 密码
        // 将registerPhoneDto的值附给user
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        // 获得盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 给密码加密
        String userPassword = MD5Utils.encrypByMd5(salt + password);
        user.setPassword(userPassword);
        // 设置盐值
        user.setSalt(salt);
        return user;
    }

    private Logininfo User2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        // 设置类型
        logininfo.setType(1);
        return logininfo;
    }
}
